package com.market2.utils.converter.impl;


import com.market2.dto.ActionDto;
import com.market2.model.Action;
import com.market2.model.Investisseur;
import com.market2.model.Societe;
import com.market2.utils.converter.Converter;

public class ActionConverter extends Converter
{	
	@SuppressWarnings("unchecked") @Override
	public ActionDto convertTo(Object source)
	{
		if(source == null || !(source instanceof Action)) {
			return null;
		}
		
		ActionDto result = new ActionDto();
		Action action = (Action) source;
		
		result.setNumero(action.getNumero());
		result.setValeurUnitaire(action.getValeurUnitaire());
		result.setQuantite(action.getQuantite());
		
		result.setIsin(action.getIsin());
		
		if(action.getTitulaire() != null) {
			result.setTitulaire(action.getTitulaire().getLogin());
		}
		
		if(action.getSociete() != null) {
			result.setSociete(action.getSociete().getNom());
		}
		
		return result;
	}

	@SuppressWarnings("unchecked") @Override
	public Action convertFrom(Object source)
	{
		if(source == null || !(source instanceof ActionDto)) {
			return null;
		}
		
		Action result = new Action();
		ActionDto actionDto = (ActionDto) source;
		
		result.setNumero(actionDto.getNumero());
		result.setValeurUnitaire(actionDto.getValeurUnitaire());
		result.setQuantite(actionDto.getQuantite());
		
		result.setIsin(actionDto.getIsin());
		
		Investisseur titulaire = getEntityManager().find(Investisseur.class, actionDto.getTitulaire());
		Societe societe = getEntityManager().find(Societe.class, actionDto.getSociete());
		
		result.setTitulaire(titulaire);
		result.setSociete(societe);
		
		return result;
	}
}
